//
//  modalViewController.m
//  唧歪
//
//  Created by MWJ on 15/8/16.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "modalViewController.h"
#import "AppDelegate.h"
#import "Comment.h"
//#import "CommentCell.h"
#import "PostDetailsViewController.h"
#import "pictureDetailViewController.h"  //全部图片界面
#import "GradientButton.h"
#import "AllCommentViewController.h"
#import "ImageCompression.h"
#import "commCell.h"
#define nextURL @"https://app.jiwaipro.com:8888/index.php/JiWai/aaa"
#define PostdetailsURL @"https://app.jiwaipro.com:8888/index.php/JiWai/postAccording"
#define reportURL @"https://app.jiwaipro.com:8888/index.php/JiWai/report"
#define myFocuscancelURL @"https://app.jiwaipro.com:8888/index.php/JiWai/cancelfocus"
#define myFocusURL @"https://app.jiwaipro.com:8888/index.php/JiWai/focus"

@interface modalViewController (){
    AppDelegate *app;
    NSString *mess_tag;
    NSString *userId;
    NSString *audiopath;
    NSMutableArray *commentArray;
    NSMutableArray *postDetailArray;
    commCell *cell;
    NSString *strIdentifier;
    NSString *strIdentifier1;
    UIAlertView *_alert;
    NSString *contentStr;
    NSString *audioTime;
    int aaaa;
    int bbbb;
    UIImageView *img;
    NSMutableArray *nextArray;
    int nextInt;
    UIImageView *wf;
    NSString *reportStr;
    NSMutableArray *postimageArray;
    int index;
    int imgcount;
    int allCount;
    NSMutableArray *imageArray;
    UIScrollView *bigScroll;
    UIView *bigView;
    NSString *contentText;
    UIButton *chakanbutton;
    NSMutableArray *focusArray;
    NSString *focusStr;
    NSString *cellContent;
}

@end

@implementation modalViewController
-(void)viewWillAppear:(BOOL)animated{
}
- (void)viewDidLoad {
    [super viewDidLoad];
    app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (app.user_id == nil || [app.user_id isEqualToString:@""]) {
        self.jvBao.hidden = YES;
    }else{
        self.jvBao.hidden = NO;
    }
    nextInt = 0;
    focusArray = [NSMutableArray array];
    postimageArray = [NSMutableArray array];
    nextArray = [NSMutableArray array];
    imageArray = [NSMutableArray array];
    [self loading];
    NSString *poststr =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
    [self nextPath:nextURL Str:poststr];
    CGFloat R1  = (CGFloat) 255/255.0;
    CGFloat G1 = (CGFloat) 255/255.0;
    CGFloat B1 = (CGFloat) 255/255.0;
    CGFloat alpha1 = (CGFloat) 0.5;
    CGFloat R2  = (CGFloat) 255/255.0;
    CGFloat G2 = (CGFloat) 255/255.0;
    CGFloat B2 = (CGFloat) 255/255.0;
    CGFloat alpha2 = (CGFloat) 0;
    UIColor *myColorRGB1 = [ UIColor colorWithRed: R1  green: G1  blue: B1  alpha: alpha1 ];
    UIColor *myColorRGB2 = [ UIColor colorWithRed: R2  green: G2  blue: B2  alpha: alpha2 ];
    self.audioView.backgroundColor = myColorRGB2;
    self.commentTableview.backgroundColor = myColorRGB2;
    self.view.backgroundColor = myColorRGB1;
    self.message_content.backgroundColor = myColorRGB2;
    
    self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    
    self.leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    self.rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    
    [self.view addGestureRecognizer:self.leftSwipeGestureRecognizer];
    [self.view addGestureRecognizer:self.rightSwipeGestureRecognizer];
}

- (void)handleSwipes:(UISwipeGestureRecognizer *)sender
{
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
        if (nextArray.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"附近已经没有帖子了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            if (nextInt < nextArray.count) {
                postDetailArray = [NSMutableArray array];
                app.appmessageid = nextArray[nextInt];
                NSString *poststr =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
                [self londingPath1:PostdetailsURL Str1:poststr];
                nextInt++;
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"附近已经没有帖子了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
//                nextInt--;
            }
        }

    }
    
    if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
        if ([nextArray containsObject:app.appmessageid]) {
        if ([app.appmessageid isEqualToString:nextArray[0]]){
            postDetailArray = [NSMutableArray array];
            app.appmessageid = app.appmeid;
            NSString *poststr =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
            [self londingPath1:PostdetailsURL Str1:poststr];
            nextInt = 0;
        }else{
            nextInt = nextInt-2;
            app.appmessageid = nextArray[nextInt];
            postDetailArray = [NSMutableArray array];
            NSString *poststr =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
            [self londingPath1:PostdetailsURL Str1:poststr];
            nextInt++;
        }
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前是第一篇帖子" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            nextInt = 0;
        }
    }
}
-(void)nextPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        nextArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(nextData:) withObject:nextArray waitUntilDone:YES];
    }];
}
-(void)nextData:(NSMutableArray *)sender{
   }
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        postDetailArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:postDetailArray waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
    app.appdetailArray = postDetailArray;
    focusArray = [NSMutableArray array];
    self.message_content.hidden = YES;
    self.message_content.text = @"";
    self.messagevoice.hidden = YES;
    [self.scrllImage removeFromSuperview];
    [img removeFromSuperview];
    [chakanbutton removeFromSuperview];
    [commentArray removeAllObjects];
    
    [self loading];
}
-(void)loading{
    commentArray = [NSMutableArray array];
    [self.messagevoice setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    self.headImage.layer.masksToBounds = YES;
    self.headImage.layer.cornerRadius = self.headImage.bounds.size.width/2;
    if (app.user_id == nil || [app.user_id isEqualToString:@""]) {
        self.FocusButton.hidden = YES;
    }else{
    if (app.appdetailArray[app.appdetailArray.count-1] == [NSNull null]) {
        self.FocusButton.hidden = NO;
        [self.FocusButton setTitle:@"关注" forState:UIControlStateNormal];
        NSLog(@"关注一下吧");
    }else{
        for (NSDictionary *dic in app.appdetailArray[app.appdetailArray.count-1]) {
            [focusArray addObject:dic[@"focususer_id"]];
        }
        if ([focusArray containsObject:app.user_id]) {
            self.FocusButton.hidden = NO;
            [self.FocusButton setTitle:@"取消关注" forState:UIControlStateNormal];
        }else{
            if ([app.user_id isEqualToString:[NSString stringWithFormat:@"%@",app.appdetailArray[1][0][@"user_id"]]]) {
                self.FocusButton.hidden = YES;
            }else{
                self.FocusButton.hidden = NO;
                [self.FocusButton setTitle:@"关注" forState:UIControlStateNormal];
            }
        }
        }
    }
    [self.FocusButton addTarget:self action:@selector(focusAction) forControlEvents:UIControlEventTouchUpInside];
    NSString *headportrait = [NSString stringWithFormat:@"%@",app.appdetailArray[0][0][@"user_headPortrait"]];
    NSURL *url=[NSURL URLWithString:headportrait];
    self.headImage.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    NSString *phoneStr = [NSString stringWithFormat:@"%@",app.appdetailArray[0][0][@"user_phone"]];
    //把手机号码的中间五位换成 *
    NSString *star=[phoneStr stringByReplacingCharactersInRange:NSMakeRange(3, 5) withString:@"***"];
    self.phoneNumber.text  = [NSString stringWithFormat:@"%@",star];
    userId = [NSString stringWithFormat:@"%@",app.appdetailArray[1][0][@"user_id"]];
    self.message_time.text=[NSString stringWithFormat:@"%@",app.appdetailArray[1][0][@"message_time"]];  //帖子发布时间
    self.message_showtime=[NSString stringWithFormat:@"%@",app.appdetailArray[1][0][@"message_showtime"]];  //帖子显示时长
    self.message_content.text=[NSString stringWithFormat:@"%@ \n\n",app.appdetailArray[1][0][@"message_content"]];   //帖子内容
    contentText = self.message_content.text;
    self.returnlab.text = [NSString stringWithFormat:@"回帖数：%@",app.appdetailArray[1][0][@"message_comment"]]; //帖子评论数
    self.message_browse.text = [NSString stringWithFormat:@"浏览数：%@",app.appdetailArray[1][0][@"message_browse"]]; //浏览数
    mess_tag = [NSString stringWithFormat:@"%@",app.appdetailArray[1][0][@"message_tag"]]; //帖子类型
    
    //经纬度转换成地址
    CLLocationCoordinate2D coordinate;
    coordinate. latitude =  [[ NSString stringWithFormat : @"%@" , app.appdetailArray[1][0][@"message_latitude"] ] floatValue ];
    coordinate. longitude = [[ NSString stringWithFormat : @"%@" , app.appdetailArray[1][0][@"message_longitude"] ] floatValue ];
    CLGeocoder *geocoder=[[ CLGeocoder alloc ] init ];
    CLLocation *newLocation=[[ CLLocation alloc ] initWithLatitude :coordinate. latitude longitude : coordinate. longitude ];
    [geocoder reverseGeocodeLocation :newLocation completionHandler :^( NSArray * placemarks, NSError * error)
     {
         MKPlacemark *placemark = [placemarks objectAtIndex : 0 ];
         
         self.message_place.text = [ NSString stringWithFormat : @"%@%@" ,  placemark. subLocality , placemark.thoroughfare];
     }];
    // 计时器
    NSTimer *countdownTimer=[[NSTimer alloc]init];
    countdownTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TheCountDown) userInfo:nil repeats:YES];
    [self messagemethods];
    if ([mess_tag isEqualToString:@"2"]) {
        [self messageAudio];
    }
}
-(void)focusAction{
    NSString *string = [NSString stringWithFormat:@"myuser_id=%@&heuser_id=%@",app.user_id,app.appdetailArray[1][0][@"user_id"]];
    if ([self.FocusButton.titleLabel.text isEqualToString:@"关注"]) {
        [self focusPath:myFocusURL Str:string];
        [self.FocusButton setTitle:@"取消关注" forState:UIControlStateNormal];
    }else if([self.FocusButton.titleLabel.text isEqualToString:@"取消关注"]){
        [self focusPath:myFocuscancelURL Str:string];
        [self.FocusButton setTitle:@"关注" forState:UIControlStateNormal];
    }
}
-(void)focusPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        focusStr =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(focusData) withObject:focusStr waitUntilDone:YES];
    }];
}
-(void)focusData{
}
-(void)messageAudio{
    if ([audioTime intValue] >=10&[audioTime intValue] <=60) {
        aaaa = [audioTime intValue] - 10;
        bbbb = ([UIScreen mainScreen].bounds.size.width - 100)/50;
    }else if([audioTime intValue] >=60){
        audioTime = @"60";
        aaaa = [audioTime intValue] - 10;
        bbbb = ([UIScreen mainScreen].bounds.size.width - 100)/50;
    }else{
        aaaa = 0;
        bbbb = 0;
    }
    img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 2, 80 + aaaa * bbbb, 30)];
    wf = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 20, 20)];
    img.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(audioplay)];
    [img addGestureRecognizer:singleTap];//点击图片事件
    wf.image = [UIImage imageNamed:@"wifi3.png"];
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(img.bounds.size.width-30, 5, 30, 20)];
    lab.font = [UIFont fontWithName:@"arail" size:14];
    lab.text = [NSString stringWithFormat:@"%@s",audioTime];
    img.backgroundColor = [UIColor colorWithRed:252/255.0 green:208/255.0 blue:30/255.0 alpha:1];
    CALayer * layer = [img layer];
    [layer setCornerRadius:8.0];
    layer.borderColor = [[UIColor grayColor] CGColor];
    layer.borderWidth = 1;
    //添加四个边阴影
    img.layer.shadowColor = [UIColor blackColor].CGColor;
    img.layer.shadowOffset = CGSizeMake(0, 0);
    img.layer.shadowOpacity = 0.5;
    img.layer.shadowRadius = 10.0;
    //给iamgeview添加阴影 < wbr > 和边框
    //添加两个边阴影
    img.layer.shadowColor = [UIColor blackColor].CGColor;
    img.layer.shadowOffset = CGSizeMake(4, 4);
    img.layer.shadowOpacity = 0.5;
    img.layer.shadowRadius = 2.0;
    [img addSubview:wf];
    [img addSubview:lab];
    [self.audioView addSubview:img];
}
-(void)TheCountDown{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSDateFormatter * dm = [[NSDateFormatter alloc]init];
    //指定输出的格式   这里格式必须是和上面定义字符串的格式相同，否则输出空
    [dm setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate * newdate = [dm dateFromString:self.message_time.text];
    int showtimeint = [self.message_showtime intValue];
    int dd = [newdate timeIntervalSince1970] + showtimeint*60 - (long)[datenow timeIntervalSince1970];
    if (dd<=0) {
        self.remaining.text = @"00:00:00";
    }else{
    int h = (dd / 60 / 60);
    int m = (dd - h * 60 * 60) / 60;
    int s = ((dd - h * 60 * 60 - m * 60));
    self.remaining.text=[NSString stringWithFormat:@"%d:%d:%d",h,m,s];
    [self.remaining setFont:[UIFont fontWithName:@"Helvetica-BoldOblique" size:14]];
    dd --;
    }
}
-(void)photoTapped{
    pictureDetailViewController *picVC=[self.storyboard instantiateViewControllerWithIdentifier:@"picDetailVC"];
    [self.navigationController pushViewController:picVC animated:YES];
}
-(void)messagemethods{
    if (app.appdetailArray[app.appdetailArray.count-2] == [NSNull null]) {
        [self.commentTableview reloadData];
    }else{
        for (NSDictionary *dic in app.appdetailArray[app.appdetailArray.count-2]) {
            Comment *co = [[Comment alloc]init];
            co.comment_content = dic[@"comment_content"];
            co.comment_time = dic[@"comment_time"];
            co.comment_heardPortrait = dic[@"comment_headPortrait"];
            co.comment_identifier = dic[@"comment_identifier"];
            co.user_phone = dic[@"user_phone"];
            co.comment_image = dic[@"comment_image"];
            co.comment_audio = dic[@"comment_audio"];

            
            [commentArray addObject:co];
        }
        [self.commentTableview reloadData];
    }
        if ([mess_tag isEqualToString:@"0"]) { //纯文字或者文字图
            if (app.appdetailArray[2] == [NSNull null]) {
            }else{
                index = (int)self.message_content.text.length;
                postimageArray = app.appdetailArray[2];
                allCount = (int)postimageArray.count;
                if (postimageArray.count>=3) {
                    imgcount = 3;
                }else{
                    imgcount = (int)postimageArray.count;
                }
                for (int i=0; i<imgcount; i++) {
                NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",app.appdetailArray[2][i][@"image_path"]]];
                UIImage *immmm = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                    [imageArray addObject:immmm];
                ImageCompression *ima = [[ImageCompression alloc]init];
                [ima OriginImage:immmm scaleToSize:CGSizeMake(([UIScreen mainScreen].bounds.size.width-35)/3, ([UIScreen mainScreen].bounds.size.width-35)/3)];
                NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:self.message_content.attributedText];
                NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil] ;
                textAttachment.image = ima.scaledImage;
                
                NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment] ;
                [string insertAttributedString:textAttachmentString atIndex:index];//index为用户指定要插入图片的位置
                    index++;
                    
                    NSAttributedString *black = [[NSAttributedString alloc]initWithString:@"\n"];
                    [string appendAttributedString:black];
                self.message_content.attributedText = string;
                
                }
                CGSize deSize = [self.message_content sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width,CGFLOAT_MAX)];
                chakanbutton = [[UIButton alloc] initWithFrame:CGRectMake(self.message_content.size.width-90, deSize.height-30, 80, 20)];
                chakanbutton.backgroundColor = [UIColor clearColor];
                [chakanbutton.titleLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]];
                [chakanbutton setTitle:@"查看大图" forState:UIControlStateNormal];
                [chakanbutton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                [chakanbutton addTarget:self action:@selector(ImageText) forControlEvents:UIControlEventTouchUpInside];
                [self.message_content addSubview:chakanbutton];
                app.appimageArray = app.appdetailArray[2];
            }

        self.message_content.hidden = NO;
    }else if ([mess_tag isEqualToString:@"1"]){  //纯图片
        postimageArray = app.appdetailArray[2];
        allCount = (int)postimageArray.count;
        if (postimageArray.count>=3) {
            imgcount = 3;
        }else{
            imgcount = (int)postimageArray.count;
        }
        CGFloat width=self.scrllImage.bounds.size.height-20;
        CGFloat height=self.scrllImage.bounds.size.height-20;
        for (int i = 0; i < imgcount; i++) {
            NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",app.appdetailArray[2][i][@"image_path"]]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            [imageArray addObject:image];
        }
        for (int j=0; j<imageArray.count; j++) {
            
            UIImageView *imageView=[[UIImageView alloc] initWithImage:imageArray[j]];
            [imageView setFrame:CGRectMake(j*width+j*10, 0, width, height)];
            [self.scrllImage addSubview:imageView];
            imageView.tag = j + 1000;
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ImageText)];
            [imageView addGestureRecognizer:gest];
            
        }
        [self.scrllImage setBounces:NO];
        //设置水平方向的滚动条:
        [self.scrllImage setShowsHorizontalScrollIndicator:NO];
        //设置ScrollView的总体的宽度(关键)：
        [self.scrllImage setContentSize:CGSizeMake((imageArray.count) * (width+10), height)];
        //设置分页:
        [self.scrllImage setPagingEnabled:YES];
        self.scrllImage.hidden = NO;
        app.appimageArray = app.appdetailArray[2];
    }else{
        self.messagevoice.hidden = NO;
        self.audioView.hidden = NO;
        for (NSDictionary *ypdic in app.appdetailArray[app.appdetailArray.count-3]) {
            audioTime = ypdic[@"audio_time"];
            audiopath = ypdic[@"audio_path"];
    }
    }
    

}

#pragma mark - 图文时候点击大图
-(void)ImageText{
    CGFloat width = 0.0;
    bigView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    bigView.backgroundColor = [UIColor colorWithRed: 0/255.0  green: 0/255.0  blue: 0/255.0  alpha: 0.9];
    [self.view addSubview:bigView];
    
    if ([mess_tag isEqualToString:@"0"]) {
        bigScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,  [UIScreen mainScreen].bounds.size.height-80)];
        [self.view addSubview:bigScroll];
    }else{
        bigScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,  [UIScreen mainScreen].bounds.size.height)];
        [self.view addSubview:bigScroll];
    }
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height-80, [UIScreen mainScreen].bounds.size.width-40, 60)];
    [bigView addSubview:textView];
    textView.textColor = [UIColor whiteColor];
    textView.backgroundColor = [UIColor colorWithRed: 255/255.0  green: 255/255.0  blue: 255/255.0  alpha: 0];
    textView.editable = NO;
    textView.text = contentText;
    
    for (int j=0; j<allCount; j++) {
        ImageCompression *ima = [[ImageCompression alloc]init];
        NSURL *url = [NSURL URLWithString:app.appdetailArray[2][j][@"image_path"]];
        UIImage *bigpic = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        if (bigpic.size.width<[UIScreen mainScreen].bounds.size.width) {
            width = bigpic.size.width ;
        }else{
            width = [UIScreen mainScreen].bounds.size.width;
        }
        [ima OriginImage:bigpic scaleToSize:CGSizeMake(width, bigpic.size.height/bigpic.size.width*width)];
        UIImageView *imageView=[[UIImageView alloc] initWithImage:ima.scaledImage];
        [imageView setFrame:CGRectMake(j*[UIScreen mainScreen].bounds.size.width+([UIScreen mainScreen].bounds.size.width-width)/2, ([UIScreen mainScreen].bounds.size.height-bigpic.size.height/bigpic.size.width*width)/2, width,  bigpic.size.height/bigpic.size.width*width)];
        [bigScroll addSubview:imageView];
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bigCancelClick)];
        [imageView addGestureRecognizer:gest];
    }
    [bigScroll setBounces:NO];
    //设置水平方向的滚动条:
    [bigScroll setShowsHorizontalScrollIndicator:NO];
    if ([mess_tag isEqualToString:@"0"]) {
        //设置ScrollView的总体的宽度(关键)：
        [bigScroll setContentSize:CGSizeMake(allCount * width, [UIScreen mainScreen].bounds.size.height-80)];
    }else{
        [bigScroll setContentSize:CGSizeMake(allCount * width, [UIScreen mainScreen].bounds.size.height)];
    }
    
    //设置分页:
    [bigScroll setPagingEnabled:YES];
}

#pragma mark - 退出大图
-(void)bigCancelClick{
    [bigScroll removeFromSuperview];
    [bigView removeFromSuperview];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return commentArray.count;
    
}

#pragma mark - 返回tableview的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return 1  + size.height;
}
#pragma mark - cell的内容加载
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UINib *nib=[UINib nibWithNibName:@"commCell" bundle:nil];
    [self.commentTableview registerNib:nib forCellReuseIdentifier:@"commCell"];
    
    static NSString *cellIdentifier=@"commCell";
    cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    Comment *comm = commentArray[indexPath.row];
    cell.comment_Time.text=[NSString stringWithFormat:@"%@",comm.comment_time];
    cellContent = [NSString stringWithFormat:@"%@",comm.comment_content];

    CGFloat R  = (CGFloat) 255/255.0;
    CGFloat G = (CGFloat) 255/255.0;
    CGFloat B = (CGFloat) 255/255.0;
    CGFloat alpha = (CGFloat) 0;
    UIColor *myColorRGB = [ UIColor colorWithRed: R  green: G  blue: B  alpha: alpha ];
    cell.backgroundColor = myColorRGB;
    strIdentifier=[NSString stringWithFormat:@"%@",comm.comment_identifier];
    
    //把手机号码的中间五位换成 *
    NSString *star=[comm.user_phone stringByReplacingCharactersInRange:NSMakeRange(3, 5) withString:@"***"];
    cell.user_phone.text = [NSString stringWithFormat:@"%@",star];
    
    
    if ([strIdentifier isEqualToString:@"0"]) {
        
        if ([cellContent rangeOfString:@"[图片评论]"].location !=NSNotFound) {
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",comm.comment_image]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            cell.image = image;
            ImageCompression *ima = [[ImageCompression alloc]init];
            [ima OriginImage:image scaleToSize:CGSizeMake(30, 30)];
            // 1> 生成文本附件
            NSTextAttachment *textAttach = [[NSTextAttachment alloc] init];
            textAttach.image = ima.scaledImage;
            
            // 2> 使用文本附件创建属性文本
            NSAttributedString *strA = [NSAttributedString attributedStringWithAttachment:textAttach];
            
            cell.comment_Content.attributedText = strA;
            cell.tagStr = @"1";
            
        }else if([comm.comment_content rangeOfString:@"[语音评论]"].location !=NSNotFound) {
            cell.audiourl = [NSURL URLWithString:comm.comment_audio];
            cell.audioview.hidden = NO;
            cell.comment_Content.hidden = YES;
            cell.comment_Content.userInteractionEnabled = NO;
        }else{
            cell.comment_Content.userInteractionEnabled = NO;
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            cell.comment_Content.text=[NSString stringWithFormat:@"%@",cellContent];
        }
    }
    else{
        //部分字体变颜色
        NSRange range1=[cellContent rangeOfString:@":"];
        NSString *str = [cellContent substringWithRange:NSMakeRange(0, range1.location+1)];
        
        NSMutableAttributedString *colorStr1 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",str]];
        [colorStr1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,range1.location+1)];//长度
        NSMutableAttributedString *colorStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",cellContent]];
        NSRange range=[cellContent rangeOfString:@":"];
        [colorStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,range.location+1)];//长度
        
        
        
        if ([cellContent rangeOfString:@"[图片评论]"].location !=NSNotFound) {
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",comm.comment_image]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            cell.image = image;
            ImageCompression *ima = [[ImageCompression alloc]init];
            [ima OriginImage:image scaleToSize:CGSizeMake(30, 30)];
            // 1> 生成文本附件
            NSTextAttachment *textAttach = [[NSTextAttachment alloc] init];
            textAttach.image = ima.scaledImage;
            
            // 2> 使用文本附件创建属性文本
            NSAttributedString *strA = [NSAttributedString attributedStringWithAttachment:textAttach];
            
            [colorStr1 appendAttributedString:strA];
            
            cell.comment_Content.attributedText = colorStr1;
            
            cell.tagStr = @"1";
            
        }else if ([comm.comment_content rangeOfString:@"[语音评论]"].location !=NSNotFound) {
            cell.audiourl = [NSURL URLWithString:comm.comment_audio];
            cell.audioview.hidden = NO;
            cell.comment_Content.hidden = YES;
            cell.comment_Content.userInteractionEnabled = NO;
        }else{
            cell.comment_Content.userInteractionEnabled = NO;
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            cell.comment_Content.attributedText = colorStr;
        }
        
    }

    
    NSURL *url = [NSURL URLWithString:comm.comment_heardPortrait];
    cell.HeadPortrait.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    cell.floor.text=[NSString stringWithFormat:@"%ld",(unsigned long)indexPath.row+1];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;  //cell设置为不可点击
    [self.commentTableview   setSeparatorColor:[UIColor    whiteColor]];  //设置分割线为白色
    
    return cell;
}

-(void)audioplay{
    if (self.avPlay.playing) {
        [self.avPlay stop];
        [wf stopAnimating];
        return;
    }else{
        NSURL *url=[NSURL URLWithString:audiopath];
        NSData *data = [NSData dataWithContentsOfURL:url];
        AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithData:data error:nil];
        self.avPlay = player;
        [self.avPlay prepareToPlay];
        [self.avPlay play];
        
        wf.animationImages = [NSArray arrayWithObjects:
                                   [UIImage imageNamed:@"wifi1.png"],
                                   [UIImage imageNamed:@"wifi2.png"],
                                   [UIImage imageNamed:@"wifi3.png"], nil];
        wf.animationDuration = 1.0;
        wf.animationRepeatCount = 0;
        [wf startAnimating];
        self.avPlay.delegate = self;
    }

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [wf stopAnimating];
    
}


#pragma mark -
- (IBAction)shang:(id)sender {
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    PostDetailsViewController *postDetail = [sb instantiateViewControllerWithIdentifier:@"detailVC"];
    [tempAppDelegate.mainNavigationController pushViewController:postDetail animated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"已经销毁");
    }];
    app.quickOrNot = @"1";
}

- (IBAction)down:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"已经销毁");
    }];
}


#pragma mark - 跳转全部评论回复按钮
- (IBAction)allComment:(id)sender {
    
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    AllCommentViewController *allcomment = [sb instantiateViewControllerWithIdentifier:@"allCommentVC"];
    [tempAppDelegate.mainNavigationController pushViewController:allcomment animated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"已经销毁");
    }];
}

#pragma mark - 举报事件
- (IBAction)reportAction:(id)sender {
    NSString *poststr =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
    [self loadReportPath:reportURL Str:poststr];
}



-(void)loadReportPath:(NSString *)path Str:(NSString *)str{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        reportStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(reportData:) withObject:reportStr waitUntilDone:YES];
    }];
}
-(void)reportData:(NSString *)string{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示：" message:@"已收到您的举报信息" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    
}

@end
